const CONFIG = require('./config.js')

/**
 * HTTP请求
 */
function _request(url, method, options, load = {loading: true, tips: '加载中...'}, fn = {}) {
  let user = wx.getStorageSync('__user_info__'),
  header = {};
  if (!url) {
    return false;
  }
  if (method && method.toUpperCase() === 'XWWW') {
    header['content-type'] = 'application/x-www-form-urlencoded'
    method = 'POST'
  }
  return new Promise((resolve, reject) => {
      if (load.loading) {
          wx.showLoading({
              title: load.tips, //提示的内容,
              mask: true, //显示透明蒙层，防止触摸穿透,
              success: res => {}
          });
      }
      wx.request({
          url: url.includes('http://') || url.includes('https://') ? url : CONFIG.baseUrl + url,
          method: method ? method.toUpperCase():'GET', //请求方式
          data: options || {},//请求参数。默认为空
          dataType: "json",
          header: {
              'accessToken': user ? user.token : '',
              ...header
          }, // 设置请求的 header
          success: function(res){
              fn.success && fn.success();
              if (res.data.code !== 0 && res.data.code !== 200) {
                  wx.showModal({
                      title: "系统错误",
                      content: res.data.message,
                      confirmText: "确定",
                      showCancel: !1,
                      success: function(e) {}
                  });
              }
              resolve(res.data);
          },
          fail: function(error){
              fn.fail && fn.fail();
              wx.showModal({
                  title: "网络错误",
                  content: 'net::ERR_CONNECTION_TIMED_OUT',
                  confirmText: "确定",
                  showCancel: !1,
                  success: function(e) {}
              });
              reject(error);
          },
          complete: function(t){
              if (load.loading) { 
                  setTimeout(() => {
                      wx.hideLoading(); 
                  }, 500);
              }
              if (200 != t.statusCode && t.data && t.data.code && 500 == t.data.code) {
                  var e = t.data.message;
                  wx.showModal({
                      title: "系统错误",
                      content: e,
                      confirmText: "确定",
                      showCancel: !1,
                      success: function(e) {}
                  });
              }
              fn.complete && fn.complete();
          },
      })
  });
}

module.exports = _request